import { getAuthorize, getUserAuth } from '@/api/oneAccess'
import { loginAndGetUser } from '@/api/user'
import { clientSetting } from '@/config/client-setting'
import baseConfig from '@/config'
import router from '@/router'
import store from '@/store'

const goCustomLogin = () => {
  router.push({ path: '/login' })
}

const searchParams = (name: string) => {
  if (name) {
    const href = window.location.href
    const search = href.split('?')[1]
    const params = new URLSearchParams(search)
    return params.get(name)
  } else {
    return null
  }
}

export const isLoginBack = (value: string) => {
  return !!value && value.includes('code') && value.includes('state')
}

export const useLogoutUrl = () => {
  return new Promise(() => {
    if (clientSetting.oneAccessLogin) {
      getAuthorize().then(res => {
        console.log('oneAccess/getAuthorize请求返回参数：' + res);
        if (res.code === '1' && res.data) {
          const href = window.location.href.split('?')[0]
          const url = `${res.data}?client_id=${baseConfig.clientId}&response_type=code&state=${Date.now()}&redirect_uri=${href}`
          console.log('oneAccess请求成功url：' + url);
          window.location.replace(url)
        } else {
          goCustomLogin()
        }
      }).catch(goCustomLogin)
    } else {
      goCustomLogin()
    }
  })
}

export const initUserAuthAndMenu = () => {
  return new Promise((resolve) => {
    const params = {
      clientId: baseConfig.clientId,
      clientSecret: baseConfig.clientSecret,
      code: searchParams('code') || ''
    }
    getUserAuth(params).then(res => {
      if (res.data) {
        loginAndGetUser(res.data.loginName).then(response => {
          if (res.data) {
            store.dispatch('user/setUserStore', response.data).then(() => {
              store.dispatch('menu/getMenu').then(() => {
                router.replace('/')
              }).catch(() => {
                router.push({ path: '/403' })
              })
            })
          } else {
            resolve(response)
          }
        }).catch(resolve)
      } else {
        resolve(res)
      }
    }).catch(resolve)
  })
}
